package com.music.lib.xiami;

import com.lcx.annotation.IOCValue;
import com.lcx.exbean.LogBean;
import com.lcx.util.JsonHandler;
import com.lcx.util.StringUtil;
import com.music.lib.MusicLib;
import com.music.lib.xiami.support.Document;
import com.music.lib.xiami.support.Element;
import com.music.lib.xiami.support.Elements;
import com.music.lib.xiami.support.Jsoup;
import com.music.util.HttpClient;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.*;

@IOCValue
public class XiamiMusicLibImpl implements MusicLib{

    private static final LogBean logger = LogBean.getLogger(XiamiMusicLibImpl.class);

    @Override
    public String getLibName() {
        return "虾米网页版库";
    }

    @Override
    public int getDefaultPageSize() {
        return 0;
    }

    @Override
    public List<MusicInfo> getMusicInfo(Map<String, Object> param) {
        HttpClient.clearAll();
        String name = (String) param.get("name");
        if(name == null) return null;
        List<MusicInfo> listMusics = new ArrayList<>();
        try {
            String requestUrl = "https://www.xiami.com/search?key="+ URLEncoder.encode(name,"UTF-8")+"&pos=1";
            HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String result = null;
            try {
                HttpClient.request(requestUrl,null,bos);
                result = new String(bos.toByteArray(),"UTF-8");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Document document = Jsoup.parse(result);
            Elements elements = document.select("#page>#wrapper div.search_result_box div.result_main table.track_list tbody tr");
            if(elements!=null){
                MusicInfo musicInfo;
                Map<String,Object> otherInfo;
                for(Element e:elements){
                    musicInfo = new MusicInfo();
                    otherInfo  = new HashMap<>();
                    Elements tds = e.select("td");

                    //播放ID 或者说专辑ID
                    String aId = tds.get(0).select("input").attr("value");
                    if(aId == null) continue;
                    otherInfo.put("albumId",aId);

                    //曲名
                    musicInfo.setName(tds.get(1).text());
                    //作者
                    Elements authors = tds.get(2).select("a");
                    if(!authors.isEmpty()){
                        String a = authors.get(0).text();
                        if(authors.size()>1){
                            a += "("+authors.get(1).text()+")";
                        }
                        otherInfo.put("author",a);
                        otherInfo.put("displayName",a+" - "+musicInfo.getName());
                    }
                    //专辑
                    otherInfo.put("albumName",tds.get(3).text());

                    musicInfo.setType("mp3");
                    musicInfo.setOtherInfo(otherInfo);
                    listMusics.add(musicInfo);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return listMusics;
    }

    @Override
    public boolean supportSplitPage() {
        return false;
    }

    @Override
    public MusicInfo getDetail(MusicInfo musicInfo) {
        //https://www.xiami.com/song/playlist/id/155490/object_name/default/object_id/0/cat/json?_ksTS=1535858533103_389&callback=jsonp390
        HttpClient.clearAll();
        //lyrics //img //play_url
        long currTime = System.currentTimeMillis();
        Map<String,Object> otherInfo = musicInfo.getOtherInfo();
        if(otherInfo == null) return null;
        String albumId = (String) otherInfo.get("albumId");
        if(albumId == null) return null;
        int random = new Random().nextInt(999)*10+9;
        String referer = "https://www.xiami.com/play?ids=/song/playlist/id/"+albumId+"/object_name/default/object_id/0";
        String requstUrl = "https://www.xiami.com/song/playlist/id/"+albumId+"/object_name/default/object_id/0/cat/json?_ksTS="+currTime+"_"+random+"&callback=jsonp"+(random+1);
        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            HttpClient.addHead("referer",referer);
            HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
            HttpClient.request(requstUrl,null,bos);
            String result = new String(bos.toByteArray(),"UTF-8");
            if(result.substring(0,7).trim().startsWith("jsonp")){
                result = result.substring(result.indexOf("(")+1,result.lastIndexOf(")"));
            }
            Map<String,Object> resultInfo = JsonHandler.parseJson(result);
            if(Objects.equals(true,resultInfo.get("status")) && resultInfo.get("data") != null){
                Map<String,Object> data = (Map<String, Object>) resultInfo.get("data");
                List<Map<String,Object>> trackList = (List<Map<String, Object>>) data.get("trackList");
                if(trackList!=null && !trackList.isEmpty()){
                    Map<String,Object> dataInfo = trackList.get(0);
                    //img
                    String img = (String) dataInfo.get("album_pic");
                    otherInfo.put("img","https:"+img);
                    //播放地址
                    String playUrl = (String) dataInfo.get("location");
                    if(playUrl!=null){
                        try {
                            playUrl = XiamiUrlReader.readUrl(playUrl);
                        } catch (Exception e) {
                            logger.error("{}_解析虾米url出险问题：",getClass(),e);
                            logger.error("{}_解析虾米url：{}",getClass(),playUrl);
                            throw e;
                        }
                        musicInfo.setUrl("https://"+playUrl);
                    }

                    //歌词
                    String lrcUrl = (String) dataInfo.get("lyric_url");
                    System.out.println("歌词下载地址："+lrcUrl);
                    if(StringUtil.isNotNull(lrcUrl)){
                        try{
                            HttpClient.clearAll();
                            HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
                            ByteArrayOutputStream lrcOut = new ByteArrayOutputStream();
                            HttpClient.request("https:"+lrcUrl,null,lrcOut);
                            String lrc = new String(lrcOut.toByteArray(),"UTF-8");
                            System.out.println("下载的歌词："+lrc);
                            musicInfo.setLrc(lrc);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }

        return musicInfo;
    }

    public static void main(String[] args) {
        MusicLib musicLib = new XiamiMusicLibImpl();
        List<MusicInfo> list = musicLib.getMusicInfo(new HashMap<String,Object>(){
            {
                put("name","左边");
                put("page",1);
            }
        });
        System.out.println(list);
        System.out.println(musicLib.getDetail(list.get(0)));
    }
}
